package com.ncs.cns.activity.task;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.ncs.cns.R;
import com.ncs.cns.business.db.DBHelper;
import com.ncs.cns.business.http.HttpHelper;
import com.ncs.cns.business.service.CommonService;
import com.ncs.cns.business.service.EventService;
import com.ncs.cns.business.service.ResourceService;
import com.ncs.cns.business.service.UserService;
import com.ncs.cns.business.service.UserSessionService;
import com.ncs.cns.business.to.Event;
import com.ncs.cns.business.to.Resource;
import com.ncs.cns.business.to.TransferObject;
import com.ncs.cns.business.to.UserNcs;
import com.ncs.cns.business.util.JsonConvertor;
import com.ncs.cns.business.util.SequenceUtil;
import com.ncs.cns.framework.Constant;

public class AddEventTask extends AsyncTask<String, String, String> {
	protected HttpHelper helper;
	protected CommonService commService;
	protected UserSessionService sessionService;
	protected UserService userService;
	protected ResourceService resourceService;
	protected EventService eventService;
	protected DBHelper dbHelper;
	private List<String> photoList = null;
	private Context c;
	private Activity a;
	private Builder waitDialog;
	private AlertDialog dialog;
	public AddEventTask(List<String> photoList,Activity a, Builder waitDialog) {
		this.a = a;
		c = a.getApplicationContext();
		commService = new CommonService(c);
		sessionService = new UserSessionService(c);
		userService =new UserService(c);
		resourceService = new ResourceService(c);
		eventService = new EventService(c);
		helper = new HttpHelper(a);
		dbHelper = new DBHelper(c);
		this.photoList = photoList;
		this.waitDialog = waitDialog;
	}
	
	
	
	@Override
	protected String doInBackground(String... params) {
		this.publishProgress("");
		TransferObject to = new TransferObject();
		to.setMethodId("M003");
		Event e = new Event();
		if(photoList.size() != 0)
			e.setEventStatus("P");
		else 
			e.setEventStatus("A");
		e.setEventSubject(params[0]);
		e.setEventContent(params[1]);
		if(Constant.IS_TEST_ENVIRONMENT){e.setEventCategory("C002");}else{e.setEventCategory("C001");}
		to.setCurrentEvent(e);		
		UserNcs user = new UserNcs();
		user.setUserName(params[2]);
		user.setUserId(params[3]);
		to.setCurrentUser(user);
		JsonConvertor json = JsonConvertor.getInstance();
		if(photoList.size() > 0){
			to.setHasAttachment("true");
		}
		String objectStr =json.conver2JsonStr(to);
		List<NameValuePair> param = new ArrayList<NameValuePair>();
		param.add(new BasicNameValuePair("dataStr",objectStr));		
		String resultStr = helper.doPost(param);
		Event event = null;
		if(!resultStr.equals("")){		
			TransferObject obj = (TransferObject) json.convert2Object(resultStr, TransferObject.class);
			event = obj.getCurrentEvent();
			for(String path : photoList){
				Resource r = new Resource();
				r.setCreatedBy(user.getUserId());
				r.setEvent(event);
				r.setEventId(event.getEventId().toString());
				r.setResourceLocation(path);
				r.setResourceId(SequenceUtil.getUUID());
				resourceService.add(r);
			}
			event.setIsMy("Y");		
			event.setIsRead("Y");
			event.setEventNumberWatched(0);
			event.setIsPraise("N");
			event.setEventNumberGood(0);
			eventService.add(event);			
		}
		return resultStr;
	}
	
	@Override
	protected void onProgressUpdate(String... values) {
		super.onProgressUpdate(values);
		waitDialog.setAdapter(new BaseAdapter() {					
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				LayoutInflater inflater = LayoutInflater.from(c);
				View view = inflater.inflate(R.layout.wait_add_event,null,false);
				return view;
			}					
			@Override
			public long getItemId(int position) {
				return 0;
			}					
			@Override
			public Object getItem(int arg0) {
				return null;
			}
			
			@Override
			public int getCount() {
				return 1;
			}
		}, null);		
		dialog =  waitDialog.create();
//		LayoutInflater inflater = LayoutInflater.from(c);
//		View view = inflater.inflate(R.layout.wait_add_event,null,false);
//		dialog.setView(view);
		dialog.setCancelable(false);
		dialog.show();
	}
	
	@Override
	protected void onPostExecute(String result) {
		RadioGroup radio = (RadioGroup)a.findViewById(R.id.main_tab_group);
		if(result == null || result.equals("")){
			Toast.makeText(c, "发起围观失败,请检查你的网络或重试", Toast.LENGTH_SHORT).show();
		}
		else{
			if(photoList.size() <= 0){
				Toast.makeText(c, "发起围观成功", Toast.LENGTH_SHORT).show();
				
			}else{
				new UploadImgTask(photoList, a).execute(Constant.UPLOAD_IMG_URL,result);
				Toast.makeText(c, "发起围观成功,正在上传图片,请勿退出程序", Toast.LENGTH_LONG).show();
			}
			JsonConvertor json = JsonConvertor.getInstance();
			TransferObject obj = (TransferObject) json.convert2Object(result, TransferObject.class);
			userService.updateUserWithName(userService.getCurrentUser(), obj.getCurrentUser().getUserName());
		}
		dialog.cancel();
		
		radio.getChildAt(1).performClick(); 		
	}
}



